<template>
  <van-button class="btn-item"
    :icon="isCollected ? 'star' : 'star-o'"
    :class="{collected:isCollected}"
    :loading="isLoading"
    @click="onCollect" />
</template>

<script>
import { addCollect, cancelCollect } from '@/api/user'

export default {
  name: 'CollectArticle',
  model: {
    prop: 'isCollected',
    event: 'update-is_collected'
  },
  props: {
    isCollected: {
      type: Boolean,
      required: true
    },
    articleId: {
      type: [Number, String, Object],
      required: true
    }
  },
  data () {
    return {
      isLoading: false
    }
  },
  methods: {
    async onCollect () {
      this.isLoading = true
      try {
        if (this.isCollected) {
          // 未收藏 点击发送收藏请求
          await addCollect(this.articleId)
        } else {
          // 已收藏 点击发送取消收藏请求
          await cancelCollect(this.articleId)
        }

        // 更新视图
        this.$emit('update-is_collected', !this.isCollected)
        this.$toast.success(!this.isCollected ? '收藏成功' : '取消收藏')
      } catch (err) {
        console.log(err)
        this.$toast.fail('操作失败，请重试')
      }
      this.isLoading = false
    }
  }
}
</script>

<style scoped lang="less">
.collected {
  .van-icon {
    color: #ffa500;
  }
}
</style>
